//
//  UITextField+Ex.m
//  CNstorm
//
//  Created by 陈家将 on 2017/1/17.
//  Copyright © 2017年 chenjiajiang. All rights reserved.
//

#import "UITextField+Ex.h"
#import "SwizzlingDefine.h"

@implementation UITextField (Ex)

+ (void)load {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        swizzling_exchangeMethod([self class] ,@selector(setPlaceholder:), @selector(setKm_Placeholder:));
    });
}

// 设置占位文字,并且设置占位文字颜色
- (void)setKm_Placeholder:(NSString *)placeholder {
    // 设置占位文字
    [self setKm_Placeholder:placeholder];

    if ([self isKindOfClass:NSClassFromString(@"PasswordTextFiled")] || [self isKindOfClass:NSClassFromString(@"LoginNameTextFiled")]) {
        // 设置占位文字颜色
        [self setPlaceholderColor:self.placeholderColor];
        // 设置占位文字大小
        [self setPlaceholderFont:self.placeholderFont];
    }
}

// 设置占位文字颜色
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
    // 1.把占位文字颜色先保存
    objc_setAssociatedObject(self, @"placeholderColor", placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    // 2.等真正设置占位文字的时候,在去设置占位文字颜色
    
    // 获取占位文字控件
    UILabel *placeholderLabel = [self valueForKey:@"placeholderLabel"];
    
    // 拿到控件去设置颜色
    placeholderLabel.textColor = placeholderColor;
    
}

// 返回占位文字颜色
- (UIColor *)placeholderColor {
    return objc_getAssociatedObject(self, @"placeholderColor");
}

// 设置占位文字大小
- (void)setPlaceholderFont:(UIFont *)placeholderFont {
    // 1.把占位文字颜色先保存
    objc_setAssociatedObject(self, @"placeholderFont", placeholderFont, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    // 2.等真正设置占位文字的时候,在去设置占位文字颜色
    
    // 获取占位文字控件
    UILabel *placeholderLabel = [self valueForKey:@"placeholderLabel"];
    
    // 拿到控件去设置大小
    placeholderLabel.font = placeholderFont;
    
}

// 返回占位文字大小
- (UIColor *)placeholderFont {
    return objc_getAssociatedObject(self, @"placeholderFont");
}


- (NSRange)selectedRange {
    UITextPosition* beginning = self.beginningOfDocument;
    
    UITextRange* selectedRange = self.selectedTextRange;
    UITextPosition* selectionStart = selectedRange.start;
    UITextPosition* selectionEnd = selectedRange.end;
    
    const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
    const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
    
    return NSMakeRange(location, length);
}

- (void)setSelectedRange:(NSRange) range { // 备注：UITextField必须为第一响应者才有效
    UITextPosition* beginning = self.beginningOfDocument;
    
    UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];
    UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
    UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
    
    [self setSelectedTextRange:selectionRange];
}


@end
